const fs = require("fs");
const inquirer = require("inquirer");
const execa = require("execa");
let hostInquirer = [
  {
    type: "input",
    message: "请输入ip地址：",
    name: "hostIp",
    validate(val) {
      let reg = /^\d+\.\d+\.\d+\.\d+$/;
      let flag = true;
      let arr = val.split(".");
      arr.forEach((val) => {
        if (flag < 0 || val > 255) {
          flag = false;
        }
      });
      if (flag && reg.test(val)) {
        return true;
      } else {
        return `请输入标准IPv4地址！！！`;
      }
    },
  },
  {
    type: "input",
    message: "请输入代理域名，多个以空格分开：",
    name: "hostAddr",
  },
];
module.exports = (option) => {
  if (option.open) {
    execa("code C:/Windows/System32/drivers/etc/hosts");
  } else {
    console.log(
      fs.readFileSync("C:/Windows/System32/drivers/etc/hosts", {
        encoding: "utf-8",
      })
    );
    if (option.add) {
      inquirer.prompt(hostInquirer).then((res) => {
        fs.writeFileSync(
          "C:/Windows/System32/drivers/etc/hosts",
          `${res.hostIp} ${res.hostAddr}`,
          { flag: "as" }
        );
      });
    }
  }
};
